package com.vinoxm.rss.service;

import com.vinoxm.rss.dao.RssDao;
import com.vinoxm.rss.dao.RssResultDao;
import com.vinoxm.rss.dao.RssTrackerDao;
import com.vinoxm.rss.model.RssTracker;
import com.vinoxm.rss.vo.RssResultVo;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.vinoxm.rss.subscribe.TrackerHandler.torrentHandler;


//@Service
@Log4j2
public class RssAlterationService {

    @Setter(onMethod_ = @Resource)
    private RssResultDao rssResultDao;

    @Setter(onMethod_ = @Resource)
    private RssTrackerDao rssTrackerDao;

    @Setter(onMethod_ = @Resource)
    private RssDao rssDao;

    @Setter(onMethod_ = @Resource)
    private RssResultService rssResultService;

    @Transactional
    @Deprecated
    public void rssResultHandler01() {
        List<RssResultVo> list = rssResultDao.selAll();
        Set<RssTracker> trackers = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            RssResultVo rssResult = list.get(i);
            rssResult.setId((long)i + 1);
            List<RssTracker> trs = torrentHandler(rssResult);
            if (trs.size() > 0) rssResult.setTrackers(trs.stream().map(RssTracker::getHost).collect(Collectors.toList()));
            trackers.addAll(trs);
        }
        Long maxId = rssTrackerDao.selMaxTrackerId();
        List<RssTracker> collect = new ArrayList<>(trackers);
        for (int i = 0; i < collect.size(); i++) {
            collect.get(i).setId(i + maxId + 1);
        }
        rssTrackerDao.insertManyTrackerWithId(collect);
        List<RssTracker> trackerList = rssTrackerDao.selAll();
        list.forEach(rssResult -> {
            List<String> trs = rssResult.getTrackers();
            if (null != trs){
                String tracker = trackerList.stream().filter(t -> trs.contains(t.getHost())).map(t -> t.getId().toString()).collect(Collectors.joining(","));
                rssResult.setTracker(tracker);
            }
        });
        log.info(list);
        rssResultDao.insertAll(list);
    }

    @Transactional
    @Deprecated
    public void rssResultHandler02() {
        List<RssResultVo> list = rssResultDao.selAllWithoutEpisode();
        for (RssResultVo result : list) {
            rssResultService.handleRssResultEpisode(result);
            rssDao.updateOneResultById(result);
        }
    }
}
